import { DomService, FormComponentType, FormViewModel } from '@farris/designer-services';
import { DgControl } from '@farris/designer-ui';
import { ViewModelNameService } from './view-model-name.service';

/**
 * 按照组件引用顺序构造视图模型列表
 */
export class ViewModelListBuilder {

    constructor(private domService: DomService) { }

    resolveViewModelList(): { viewModelTabs: any[], activeViewModel: FormViewModel } {
        if (!this.domService.module) {
            return;
        }
        const vmNameService = new ViewModelNameService(this.domService);
        const viewModelTabs = [];

        const viewModels = this.sortViewModels();
        viewModels.forEach(vm => {
            if (vm.fakeDel) {
                return;
            }
            const showName = vmNameService.getViewModelName(vm.id, vm.name);
            if (showName) {
                const cmp = this.domService.getComponentByVMId(vm.id);
                viewModelTabs.push({ id: vm.id, name: showName, componentId: cmp.id });
            }
        });
        return { viewModelTabs, activeViewModel: viewModels[0] };

    }
    /**
     * 按照组件引用的顺序排列ViewModel节点
     */
    private sortViewModels() {
        const rootCmp = this.domService.getComponentById('root-component');
        const cmpIdList = [];
        this.getAllCmpIdsBySort(rootCmp, cmpIdList);
        const components = this.domService.components.filter(c => c.componentType !== 'Frame');
        const sortedViewModels = [];
        sortedViewModels.push(this.domService.getViewModelById(rootCmp.viewModel));
        cmpIdList.forEach(cmpId => {
            const cmp = components.find(c => c.id === cmpId);
            sortedViewModels.push(this.domService.getViewModelById(cmp.viewModel));
        });
        return sortedViewModels;
    }

    private getAllCmpIdsBySort(domJson: any, cmpIdList: string[]) {
        if (!domJson) {
            return cmpIdList;
        }
        if (domJson.type === DgControl.ComponentRef.type) {
            cmpIdList.push(domJson.component);

            // 列表弹出编辑/侧边栏编辑：单独处理
            const cmpNode = this.domService.getComponentById(domJson.component);
            if (cmpNode && cmpNode.componentType === FormComponentType.dataGrid) {
                const dataGrid = this.domService.selectNode(cmpNode, n => n.type === DgControl.DataGrid.type && n.enableEditByCard !== 'none' && n.modalComponentId);
                if (dataGrid) {
                    const modalFrameCmp = this.domService.getComponentById(dataGrid.modalComponentId);
                    cmpIdList.push(dataGrid.modalComponentId);
                    this.getAllCmpIdsBySort(modalFrameCmp, cmpIdList);
                }
            }
        }

        if (!domJson.contents || domJson.contents.length === 0) {
            return cmpIdList;
        }
        for (const content of domJson.contents) {

            this.getAllCmpIdsBySort(content, cmpIdList);
        }
        return cmpIdList;
    }

}
